/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package Controller;

import com.mysql.jdbc.Driver;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 *
 * @author ben
 */
public class DataProvider {
    
    private Connection connection;
    
    public Connection Open()
        {
            try {
                Driver d = new Driver();
                DriverManager.registerDriver(d);
                String url="jdbc:mysql://localhost/congtyduongsat";
                String user="root";
                String pass="";
                this.connection = DriverManager.getConnection(url,user,pass);
            } 
            catch (SQLException ex) {
                System.err.println(ex.getMessage());
            }
            return null;
        }
    
    public void Close(){
        try {
            this.connection.close();
        } catch (SQLException ex) {
            System.err.printf(ex.getMessage());
        }
    }
    
    public ResultSet ExecuteQuery(String sql){
       ResultSet rs = null;
       
        try {
            Statement sm = this.connection.createStatement();
            rs = sm.executeQuery(sql);
        } catch (SQLException ex) {
            System.err.printf(ex.getMessage());
        }
        
        return rs;
    }
    
    public int ExecuteUpdate(String sql){
        int n = -1;
        
        try {
            Statement sm = this.connection.createStatement();
            n = sm.executeUpdate(sql);
        } catch (SQLException ex) {
            System.err.printf(ex.getMessage());
        }
        
        return n;
    }
   
    public String MD5(String input) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] messageDigest = md.digest(input.getBytes());
            BigInteger number = new BigInteger(1, messageDigest);
            String hashtext = number.toString(16);
            while (hashtext.length() < 32) {
                hashtext = "0" + hashtext;
            }
            return hashtext;
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }
}
